package threadcoreknowledge.stopthreads;

/**
 * 中断线程最优方法之 优先抛出
 * 最佳实践：catch了InterruptedException之后的优先选择：在方法签名中抛出异常
 * 那么在run() 就会强制 try/catch
 * https://javaweixin6.blog.csdn.net/article/details/108091887
 */
public class RightWayStopThreadInProd implements Runnable {

    @Override
    public void run() {
        // 程序会抛异常  但不会被终止 因为try在while里面
        while (true && !Thread.currentThread().isInterrupted()) {
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                // 保存日志、停止程序
                System.out.println("保存日志");
                e.printStackTrace();
            }
        }
    }

    /**
     * 做为被调用方  应该把异常抛给调用方
     * 线程中断 优先选择在方法的签名中抛出异常
     *
     * @throws InterruptedException
     */
    private void throwInMethod() throws InterruptedException {
//        try {
        Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
